<template>
  <view class="container">
    <button @click="chooseImage">拍照或选图上传</button>
    <image
      v-if="imageUrl"
      :src="imageUrl"
      mode="widthFix"
      style="width: 300px; margin-top: 20px"
    />
    <text v-if="uploadResult">{{ uploadResult }}</text>
  </view>
</template>

<script lang="ts" setup>
import { ref } from "vue";

const imageUrl = ref<string>("");
const uploadResult = ref<string>("");

function chooseImage() {
  uni.chooseImage({
    count: 1,
    sourceType: ["camera", "album"],
    success: (res) => {
      if (res.tempFilePaths.length > 0) {
        imageUrl.value = res.tempFilePaths[0];
        uploadFile(imageUrl.value);
      }
    },
    fail: () => {
      uni.showToast({ title: "选择图片失败", icon: "none" });
    },
  });
}

function uploadFile(filePath: string) {
  uni.uploadFile({
    url: "/temp/upload",
    filePath,
    name: "file",
    success: (uploadRes) => {
      const data = JSON.parse(uploadRes.data);
      if (data.code === "200") {
        uploadResult.value = "上传成功，图片地址：" + data.data;
      } else {
        uploadResult.value = "上传失败，服务器返回：" + data.message;
      }
    },
    fail: () => {
      uploadResult.value = "上传失败，请检查网络或服务器";
    },
  });
}
</script>

<style scoped>
.container {
  padding: 20px;
}
</style>
